# -*- coding:utf-8 -*- ＃
'''
Created on 2012-8-3

'''
from services import service
import unittest
import base64
from common.status_code import Status
from flask import json
from notification.gcm import GCMWrapper
from APNSWrapper.notifications import APNSNotificationWrapper, APNSNotification
import os
import binascii

class FlaskrTestCase(unittest.TestCase):

    def setUp(self):
        service.app.config['TESTING'] = True

    def tearDown(self):
        service.app.config['TESTING'] = False
        
    def test_index(self):
        tester = service.app.test_client();
        
        auth = base64.b64encode("user:!QAZ1qaz") 
        response = tester.get("/", headers=[('Authorization', "Basic " + auth)])
        
        print(str(response.data))
        
        expected_result = json.dumps({"status":Status.OK, "message":"Server is OK."}, indent=2);
        
        self.assertIsNotNone(response);
        self.assertEquals(response.status_code, 200);
        self.assertEquals(response.data if response else None, expected_result)
        
    def test_gcm_notification(self):
        """
        Tests send server push notification message via Google Cloud Messaging.
        """
        api_key = "AIzaSyCprAaXXoK09C_9o49l0RfymH7y8ZfZGGw";
        device_reg_id = "APA91bHMgJeHZb_ybW6KZN0ukqPFk_GU1yATXW6p6FM_E_bjDCmoLWLf15eWpTh939wyWRDUTfDArNh5SaRkJP8pNQmvik1aqlPYiurCywaEtMNV-1sEyOwa4y-mUDqc1whLGHP-CVlm";
        gcm = GCMWrapper(api_key);
        result = gcm.notify([device_reg_id]
                   , {"type": "1", "message": "hello, from python!"});
        self.assertEquals(result["status"], 200);
        
    def test_APN_notification(self):
        """
        Tests send server push notification message via Apple Push Notification.
        """
        deviceToken = binascii.unhexlify('c5f54de347f4608af559b8651c9a53f3edf0b15a7da29e4b964ffcc02c4f88d7');

        fileExists = os.path.exists("iphone_cert.pem");
        print("File exists: {0}\n".format(fileExists));
        self.assertEqual(fileExists, True);

        # create wrapper
        wrapper = APNSNotificationWrapper('iphone_cert.pem', True)

        # create message
        message = APNSNotification()
        message.token(deviceToken)
        message.badge(5)
        
        # just add alert text
        message.alert("You got a server push message. 你收到个短信息。")

        # enable sound (default sound if no argument)
        message.sound()

        # add message to tuple and send it to APNS server
        wrapper.append(message)
        wrapper.notify()

if __name__ == '__main__':
    unittest.main()
